const R = require('@/models/Response')
const { SystemLog } = require('@/framework/mongoose/index')
const { ERROR_SYSTEM_CODE } = require('@/constants/errorCode')
const { LOG_TYPE } = require('@/constants/log')

const catchError = async (ctx, next) => {
  try {
    await next()
  } catch (error) {
    // if (error.errorCode) {
    //   console.log('捕获到异常')
    //   return (ctx.body = errror.msg)
    // }
    // console.log(Object.keys(error), error.errors[0].message)
    console.log(error, '111')
    // 记录错误日志,到这里的日志，说明controller层没有捕获到,不是预期的异常
    const log = new SystemLog({
      type: LOG_TYPE.SYSTEM_ERROR,
      desc: error.toString(),
      ip: ctx.request.ip,
      ua: ctx.request.header['user-agent'],
      userId: ctx?.user?.id || ''
    })
    try {
      await log.save()
    } catch {}

    ctx.body = R.error(ERROR_SYSTEM_CODE.SYSTEM_ERROR)
  }
}
module.exports = catchError
